<?php
class Login extends CI_Controller {
	
	private $result = array();
	private $id_user = '00000';
	
	public function index($page = 'login')
	{
		$this->authentification('login');
	}

	public function authentification($page = 'login')
	{
		if ( ! file_exists('application/views/login/'.$page.'.php'))
		{
			// Whoops, we don't have a page for that!
			show_404();
		}
		
		$this->load->helper('form');
		$this->load->library('form_validation');
	
		$this->form_validation->set_rules('login', 'Login', 'required|callback_login_check');
		$this->form_validation->set_rules('motdepasse', 'Password', 'required|callback_password_check');
	
		if($this->form_validation->run()) {
			$this->load->model('login_model','DBLogin',TRUE);
			$this->result = $this->DBLogin->read('*', array('id' => $this->id_user));
			$connected = array('id'		=> $this->result->row('id'),
							   'nom'	=> $this->result->row('nom'),
							   'prenom'	=> $this->result->row('prenom'),
							   'login'	=> $this->result->row('login'),
							   'email'	=> $this->result->row('email'),
							   'admin'	=> $this->result->row('admin'));
			$fromlogin = array('fromlogin' => 'VRAI');
			$this->session->set_userdata($connected);
			$this->session->set_userdata($fromlogin);
			log_message('info', '### Login réussi : '.$connected['prenom'].' '.$connected['nom']);
			redirect('/commandes');
			
		} else {
			$this->session->sess_destroy();
			$this->load->library('layout');
			$this->layout->set_titre('RAVIOLES');
			$this->layout->ajouter_css('ravioles');
			$this->layout->ajouter_js('jquery');
			$this->layout->ajouter_js('jquery.corner');
			$this->layout->views('templates/header')
		    			 ->view('login/login');
		}
	}
	
	public function ajout($page = 'ajout')
	{
		if ( ! file_exists('application/views/login/'.$page.'.php'))
		{
			// Whoops, we don't have a page for that!
			show_404();
		}
        
	
		if($this->input->post('BAjoutUser') == "Retour") redirect('login');
		
		$this->load->helper('form');
		$this->load->library('form_validation');

		$this->form_validation->set_rules('nom', 'Nom', 'required');
		$this->form_validation->set_rules('prenom', 'Pr&eacute;nom', 'required');
		$this->form_validation->set_rules('email', 'E-mail', 'required|valid_email|callback_email_doublon');		
		$this->form_validation->set_rules('login', 'Login', 'required|callback_login_doublon');
		$this->form_validation->set_rules('motdepasse', 'Password', 'required');
		$this->form_validation->set_rules('motdepasse2', 'V&eacute;rification du password', 'required|matches[motdepasse]');
		
		if($this->form_validation->run()) {
			$this->load->model('login_model','DBLogin',TRUE);
			
			$champs_e = array();
			$champs_e['nom']    = $this->input->post('nom');
			$champs_e['prenom'] = $this->input->post('prenom');
			$champs_e['email']  = $this->input->post('email');
			$champs_e['login']  = $this->input->post('login');
			
			$champs_ne = array();
			$champs_ne['mdp']   = 'AES_ENCRYPT("'.$this->input->post("motdepasse").'","password")';
			
			$resultat = $this->DBLogin->create($champs_e, $champs_ne);
			
			redirect('login');		
			
		} else {
			$this->load->library('layout');
			$this->layout->set_titre('RAVIOLES');
			$this->layout->ajouter_css('ravioles');
			$this->layout->ajouter_js('jquery');
			$this->layout->ajouter_js('jquery.corner');
			$this->layout->views('templates/header')
		   				 ->view('login/ajout');
		}
	}

	function login_doublon($pseudo) { // Unicité du login dans la base de données
		$retour = TRUE;
		$this->load->model('login_model','DBLogin',TRUE);
		
		$nb_login = $this->DBLogin->count('login', $pseudo);
		if($nb_login == 1) {
			$this->form_validation->set_message('login_doublon', 'Ce nom de login est d&eacute;j&agrave; utilis&eacute;.');
			$retour = FALSE;
		}
		return $retour;
	}

	function login_check($pseudo) { // Recherche du login dans la base de données
		$retour = TRUE;
		
		if(!empty($pseudo)) {
			$this->load->model('login_model','DBLogin',TRUE);
		
			$this->result = $this->DBLogin->read('id', array('login' => $pseudo));
			if($this->result->num_rows() == 0)	{
				$this->form_validation->set_message('login_check', 'Login introuvable.');
				$retour = FALSE;
			} else { $this->id_user = $this->result->row('id'); }
		}
		return $retour;
	}

	function password_check($password) { // Vérification du mot de passe de l'ID calculé par login_check 
		$retour = TRUE;
		$this->load->model('login_model','DBLogin',TRUE);
		
		$nb_login = $this->DBLogin->count('id', $this->id_user);
		if($nb_login == 0) {
			$this->form_validation->set_message('password_check', '');
			$retour = FALSE;
		}
		if($retour)
			if(!$this->DBLogin->MotDePasse($this->id_user, $password)) {
				$this->form_validation->set_message('password_check', 'Mot de passe incorrect.');
				$retour = FALSE;
			}
				
		return $retour;
	}
	
	function email_doublon($email) { // Unicité de l'email dans la base de données
		$retour = TRUE;
		$this->load->model('login_model','DBLogin',TRUE);
		
		$nb_email = $this->DBLogin->count('email', $email);
		if($nb_email == 1) {
			$this->form_validation->set_message('email_doublon', 'Cet e-mail est d&eacute;j&agrave; utilis&eacute;.');
			$retour = FALSE;
		}
		return $retour;
	}
	
	function email_check($email) { // Recherche de l'email dans la base de données
		$retour = TRUE;
		
		if(!empty($email)) {
			$this->load->model('login_model','DBLogin',TRUE);
		
			$this->result = $this->DBLogin->read('id', array('email' => $email));
			if($this->result->num_rows() == 0)	{
				$this->form_validation->set_message('email_check', 'Email inconnu.');
				$retour = FALSE;
			}
		}
		return $retour;
	}
	
	function loginemail($loginemail) { // Equivalent 'required' mais c'est juste pour personnaliser le message d'erreur
		$retour = TRUE;
		if(empty($loginemail)) {
			$this->form_validation->set_message('loginemail', 'Vous devez renseigner au moins un login ou une adresse e-mail !');
			$retour = FALSE;
		}
		return $retour;
	}
	
	function oubli($page = "mdpoubli") {
		if ( ! file_exists('application/views/login/'.$page.'.php'))
		{
			// Whoops, we don't have a page for that!
			show_404();
		}
        
	
		if($this->input->post('BOubli') == "Retour") redirect('login');
		
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		$this->form_validation->set_rules('email', 'E-mail', 'valid_email|callback_email_check');		
		$this->form_validation->set_rules('login', 'Login', 'callback_login_check');
		$this->form_validation->set_rules('loginemail', 'loginemail', 'callback_loginemail');
		
		if($this->form_validation->run()) {
			$login = $this->input->post('login');
			$email = $this->input->post('email');
			$this->load->model('login_model','DBLogin',TRUE); // Lecture du mot de passe
			
			if(!empty($login)) { $where = array('login' => $login); } // Recherche sur le champ qui été rempli (login en priorité)
			else { $where = array('email' => $email); }
			
			$resultat = $this->DBLogin->read('login, email, AES_DECRYPT(`mdp`,\'password\') AS motdepasse', $where, FALSE); // Lecture base
			
			$user_oubli = $resultat->row(); // Tableau contenant les 3 veleurs relatives au user
			
			EnvoiMail("OUBLI", $user_oubli);
				
			$this->load->library('layout');
			$this->layout->set_titre('RAVIOLES');
			$this->layout->ajouter_css('ravioles');
			$this->layout->ajouter_js('jquery');
			$this->layout->ajouter_js('jquery.corner');
			$this->layout->views('templates/header')
		   				 ->view('login/mdpoublifin', $user_oubli);
			
		} else {
			$this->load->library('layout');
			$this->layout->set_titre('RAVIOLES');
			$this->layout->ajouter_css('ravioles');
			$this->layout->ajouter_js('jquery');
			$this->layout->ajouter_js('jquery.corner');
			$this->layout->views('templates/header')
		   				 ->views('login/mdpoubli')
		   				 ->view('templates/footer');
		}
	}
	
	function oublifin() {
		redirect("login");
	}
}

